/*************************************************************************
    > File Name: client.cpp
    > Author: Lancer
    > Mail: 18826075768@163.com
************************************************************************/

#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <fcntl.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <sys/stat.h>
using namespace std;

int main(){
    int i, fd, len;
    char* buf = "this is a daemon!\n";
    len = strlen(buf); 
    pid_t pc = fork();
    if(pc < 0){
        printf("error fork!\n");
        exit(1);
    }
    else if(pc > 0){
        exit(0);
    }

    setsid();
    chdir("/");
    umask(0);
    for(i = 0; i < 65535; i++){
        close(i);
    }
    while(1){
        if((fd = open("/tmp/daemon.log", O_CREAT | O_WRONLY | O_APPEND, 0600)) < 0){
            perror("open");
            exit(1);
        }
        write(fd, buf, len + 1);
        close(fd);
        sleep(5);
    }
    return 0;
}